const os = require('os');
const fs = require('fs');
const http = require('http');
const path = require('path');
const WebSocket = require('ws');

const html = 'web-server.html';
const server = http.createServer((req, res) => {
  const filePath = path.join(__dirname, html);
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404);
      res.end('File not found\n文件未找到');
    } else {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(data);
    }
  });
});

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

// 监听WebSocket连接
wss.on('connection', function connection(ws) {
  console.log('服务器 已连接');

  // 接收消息
  ws.on('message', function incoming(message) {
    console.log('接收的消息:', message);

    // 解析消息
    let parsedMessage;
    try {
      parsedMessage = JSON.parse(message);
    } catch (error) {
      console.error('解析消息失败:', error);
      return;
    }

    // 广播消息给所有客户端
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({type: 'message', content: parsedMessage.content}));
      }
    });
  });
});

const interfaces = os.networkInterfaces();
const addresses = [];
for (const name of Object.keys(interfaces)) {
  for (const iface of interfaces[name]) {
    if (iface.family === 'IPv4' && !iface.internal) {
      addresses.push(iface.address);
    }
  }
}

server.listen(2023, () => {
  const address = addresses[0];
  utools.copyText(`http://${address}:2023/`)
  console.log(`服务器启动成功，地址为 http://${address}:2023/`);
});
